package juc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

//线程通信
/*
A线程打印1-5
B线程打印1-10
C线程打印1-15

打印顺序为A->B->C循环10轮
 */
public class Test11 {
    public static void main(String[] args) {
        ShareData shareData = new ShareData();

        new Thread(() -> {
            for (int i = 1; i <= 10; i++) {
                try {
                    Thread.sleep(1000);
                    shareData.print5();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        },"A").start();
        new Thread(() -> {
            for (int i = 1; i <= 10; i++) {
                try {
                    Thread.sleep(1000);
                    shareData.print10();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        },"B").start();

        new Thread(() -> {
            for (int i = 1; i <= 10; i++) {
                try {
                    Thread.sleep(1000);
                    shareData.print15();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        },"C").start();
    }
}
class ShareData {
    private int num = 1;
    private Lock lock = new ReentrantLock();

    private Condition c1 = lock.newCondition();
    private Condition c2 = lock.newCondition();
    private Condition c3 = lock.newCondition();

    public void print(int number) {
        for (int i = 1; i <= number; i++) {
            System.out.println(Thread.currentThread().getName() + "\t" + i);
        }
    }

    public void print5() throws Exception {
        lock.lock();
        try {
            while (num != 1) {
                c1.await();
            }
            print(5);
            num = 2;
            c2.signal();
        } finally {
            lock.unlock();
        }
    }

    public void print10() throws Exception {
        lock.lock();
        try {
            while (num != 2) {
                c2.await();
            }
            print(10);
            num = 3;
            c3.signal();
        } finally {
            lock.unlock();
        }
    }

    public void print15() throws Exception {
        lock.lock();
        try {
            while (num != 3) {
                c3.await();
            }
            print(15);
            num = 1;
            c1.signal();
        } finally {
            lock.unlock();
        }
    }
}